#-*-coding:utf-8-*-
__author__ = 'toriycn'


import paramiko
import threading
import os,traceback


def ssh2(ip,username,passwd,cmd):
    returnContent = []
    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(ip,22,username,passwd,timeout=5)
        for m in cmd:
            stdin, stdout, stderr = ssh.exec_command(m,timeout=10)
            out = stdout.readlines()
            #屏幕输出
            outstr = []
            for o in out:
                outstr.append(o.strip())
            returnContent.append("<br>".join(outstr))
        print ('%s\tOK\n'%(ip))
        ssh.close()
    except :
        traceback.print_exc()
        return '%s\tError\n'%(ip)
    return '<br>'.join(returnContent)


def sshputfile(ip,username,passwd,local_dir,remote_dir='.' ,local_filename = None,remote_filename = None):
    try:
        ssh=paramiko.Transport((ip,22))
        ssh.connect(username=username,password=passwd)
        sftp=paramiko.SFTPClient.from_transport(ssh)
        if local_filename is not None:
            if remote_filename is None:
                remote_filename = local_filename
                sftp.put(os.path.join(local_dir,local_filename),os.path.join(remote_dir,remote_filename))
        else:
            files=os.listdir(local_dir)
            for f in files:
                sftp.put(os.path.join(local_dir,f),os.path.join(remote_dir,f))
        ssh.close()
        return "suucess"
    except :
        traceback.print_exc()
        print ('%s\tError\n'%(ip))
    return "error"

def sshgetfile(ip,username,passwd,remote_dir,local_dir = '.',remote_filename = None,local_filename = None):
    try:
        ssh=paramiko.Transport((ip,22))
        ssh.connect(username=username,password=passwd)
        sftp=paramiko.SFTPClient.from_transport(ssh)
        if remote_filename is not None:
            if local_filename is None:
                local_filename = remote_filename
                sftp.get(os.path.join(remote_dir,remote_filename),os.path.join(local_dir,local_filename))
        else:
            return "error"
        ssh.close()
        return "suucess"
    except :
        traceback.print_exc()
        print ('%s\tError\n'%(ip))
    return "error"


if __name__=='__main__':
    cmd = ['cal','df  -h']#你要执行的命令列表
    username = ""  #用户名
    passwd = ""    #密码
    threads = []   #多线程
    print ("Begin......")
    print(ssh2("123.57.154.30","mspsys","boco809fund",cmd))
    # sshputfile("123.57.154.30","mspsys","boco809fund","/Users/toriycn/workspace/studio/oschinagitproject/butterfly/orm/"
    #            ,'.','data.py')

    # for i in range(1,254):
    #     ip = '192.168.1.'+str(i)
    #     a=threading.Thread(target=ssh2,args=(ip,username,passwd,cmd))
    #     a.start()